package com.lemo.realms;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import com.lemo.entity.User;
import com.lemo.service.UserService;

public class RealmMD5SaltOne extends AuthorizingRealm {
	
	@Resource
	private UserService userService;

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auToken) throws AuthenticationException {

		System.out.println("RealmMD5SaltOne");
		UsernamePasswordToken token = (UsernamePasswordToken) auToken;
		String username = token.getUsername();

		User currentUser = userService.findUserByUserName(username);
		
		if (currentUser==null) {
			throw new UnknownAccountException("用户不存在");
		}
		Object principal = username;
		Object credentials = currentUser.getPassword();
		/*if ("admin".equals(username)) {
			credentials = "038bdaf98f2037b31f1e75b5b4c9b26e";
		} else if ("lee".equals(username)) {
			credentials = "9c4b52ebf7d205420a9b2a88734487f4";
		}*/

		ByteSource credentialsSalt = ByteSource.Util.bytes(username);

		String realmName = getName();
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal, credentials, credentialsSalt,
				realmName);
		return info;
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		Object principal = principals.getPrimaryPrincipal();

		Set<String> roles = new HashSet<>();
		roles.add("user");
		if ("admin".equals(principal)) {
			roles.add("admin");
		}
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
		return info;
	}

	public static void main(String[] args) {
		int hashIterations = 1024;
		Object salt = ByteSource.Util.bytes("lee");;
		Object source = "123456";
		String algorithmName = "MD5";
		SimpleHash simpleHash = new SimpleHash(algorithmName, source, salt, hashIterations);
		System.out.println(simpleHash);
	}

}
